package com.springmvc.interceptor;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger log = Logger.getLogger(LoginInterceptor.class);

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 在拦截点执行前拦截，如果返回true则不执行拦截点后的操作（拦截成功）
        // 返回false则不执行拦截
        HttpSession session = httpServletRequest.getSession();
        log.info("拦截到的URI请求："+httpServletRequest.getRequestURI());
        String uri = httpServletRequest.getRequestURI(); // 获取登录的uri，这个是不进行拦截的
        log.info("获取Session中的用户信息"+session.getAttribute("LOGIN_USER"));
        // if(session.getAttribute("LOGIN_USER")!=null || uri.contains("/login/index")) {// 说明登录成功 或者 执行登录功能
        if(session.getAttribute("LOGIN_USER")!=null || uri.contains("/login/userLogin.do")) {
            // 登录成功不拦截
            return true;
        }else {
            // 拦截后进入登录页面
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/index.do");
            return false;
        }
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
